package justweb

// Map结构的路由规则

import (
	"net/http"
)

// 依据map结构的路由
type handlerBaseOnMap struct {
	handlers map[string]func(c *Context)
}

func (h *handlerBaseOnMap) Key(method, pattern string) string {
	// return fmt.Sprintf("%s#%s", method, pattern)
	return method + "#" + pattern
}

// func (h *handlerBaseOnMap) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func (h *handlerBaseOnMap) ServeHTTP(c *Context) {
	// 查找得到，即成功映射；查找不到，则404
	// k := h.Key(r.Method, r.URL.Path)
	k := h.Key(c.R.Method, c.R.URL.Path)
	if handler, ok := h.handlers[k]; ok {
		// handler(NewContext(w, r))
		handler(NewContext(c.W, c.R))
	} else {
		c.W.WriteHeader(http.StatusNotFound)
		c.W.Write([]byte("no found ,404"))
	}
}

func (h *handlerBaseOnMap) Route(method string, pattern string, handlerfunc HandlerFunc, filters ...string) error {
	k := h.Key(method, pattern)
	h.handlers[k] = handlerfunc
	return nil
}

// 构建Map路由
func NewHandlerBaseOnMap() Handler { //返回接口
	return &handlerBaseOnMap{
		handlers: make(map[string]func(c *Context)),
	}
}

var _ Handler = &handlerBaseOnMap{}
